﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Church.Common;
using Church.Models.Shared;
using Church.Resources;
using DataBaseLayer.Dto;
using MvcContrib;

namespace Church.Controllers
{
	public class NewsController : Controller
	{
		#region Actions

		public ActionResult Index(int? model)
		{
			return View(model);
		}

		public ActionResult Puzzles(int? pageNumber)
		{
			var model = new PuzzlesModel();
			FillPuzzlesModel(model, pageNumber ?? 1);
			return View(model);
		}

		public ActionResult Pager(int? pageNumber)
		{
			var model = new PagerModel
			{
				CurrentPage = pageNumber.HasValue ? pageNumber.GetValueOrDefault() : 1,
				TotalCountItems = AppContext.ServiceFactory.NewsService.GetCountNews()
			};
			return View(model);
		}

		public ActionResult News(int? id)
		{
			var model = AppContext.ServiceFactory.NewsService.GetNewsById(id.GetValueOrDefault(), Constants.DEFAULT_COUNT_PUZZLES);
			if (model == null)
				return this.RedirectToAction(a => a.Index(null));
			return View(model);
		}

		#endregion

		#region Internal Implementation

		private void FillPuzzlesModel(PuzzlesModel model, int pageNumber)
		{
			if (model != null)
			{
				var data = AppContext.ServiceFactory.NewsService.GetNewsByPageNumber(pageNumber - 1, Constants.DEFAULT_COUNT_PUZZLES) ?? new List<NewsData>();
				for (var item = 0; item < data.Count() && item < Constants.DEFAULT_COUNT_PUZZLES; item++)
				{
					model.Puzzles[item].Description = data.ElementAt(item).Description;
					model.Puzzles[item].Header = data.ElementAt(item).Header;
					if (!string.IsNullOrWhiteSpace(data.ElementAt(item).ImageUrl))
						model.Puzzles[item].ImageUrl = data.ElementAt(item).ImageUrl;
					model.Puzzles[item].Url = new UrlHelper(Request.RequestContext).Action(
						"News",
						"News",
						new RouteValueDictionary { { "id", data.ElementAt(item).NewsId } });
				}
				model.FooterHelp = "Православное обозрение";
			}
		}

		#endregion
	}
}
